package by.semerikov.action;

import java.security.MessageDigest;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import by.semerikov.constants.Results;
import by.semerikov.data.SessionHandler;
import by.semerikov.exceptions.ConnectorException;
import by.semerikov.exceptions.DAOException;
import by.semerikov.form.LoginForm;
import by.semerikov.model.Person;
import by.semerikov.model.UserSession;
import by.semerikov.service.PersonService;
import by.semerikov.service.ServiceFactory;
import by.semerikov.service.UserSessionService;

public class LoginAction extends Action {
	private static final Logger log = Logger.getLogger(LoginAction.class);
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			
			LoginForm loginForm = (LoginForm) form;
			SessionHandler sh = new SessionHandler(request);
			Person user = sh.getUser();
			if (user != null) {
				return mapping.findForward(Results.SUCCESS + user.getPost());
			}
			Person p = new Person(null, null, null, null,
					loginForm.getUserName(), loginForm.getPassword());
			PersonService personService = ServiceFactory.getInstance()
					.getPersonService();
			UserSessionService userSessionService = ServiceFactory
					.getInstance().getUserSessionService();
			List<Person> lp = personService.getPersonsEqual(p);
			if (lp != null && lp.size() > 0) {
				user = lp.get(0);
				MessageDigest md = MessageDigest.getInstance("MD5");
				String str = lp.get(0).getLogin() + lp.get(0).getPassword()
						+ "Solt";
				md.update(str.getBytes());
				byte[] digest = md.digest();
				String index = digest.toString();
				userSessionService.createUserSession(new UserSession(null, lp
						.get(0).getId(), index));
				sh.setIndex(index);
				sh.setRole(user.getPost());
				sh.setUserName(user.getName());
				log.info("User" + user.getName() +  "Begin Work");
				return mapping.findForward(Results.SUCCESS + user.getPost());
			} else {
				ActionMessages errors = new ActionMessages();
				errors.add("userNotFound", new ActionMessage(
						"error.userNotFound", loginForm.getUserName()));
				saveErrors(request, errors);
				return mapping.findForward(Results.FAILURE);
			}
		} catch (DAOException e) {
			log.error(e);
			ActionMessages errors = new ActionMessages();
			errors.add("errorMessage", new ActionMessage(e.getMessage()));
			saveErrors(request, errors);
			// e.printStackTrace();
			return mapping.findForward(Results.ERROR);
		} catch (ConnectorException e) {
			log.error(e);
			ActionMessages errors = new ActionMessages();
			errors.add("errorMessage", new ActionMessage(e.getMessage()));
			saveErrors(request, errors);
			// e.printStackTrace();
			return mapping.findForward(Results.ERROR);
		} catch (Exception e) {
			log.error(e);
			ActionMessages errors = new ActionMessages();
			errors.add("errorMessage",
					new ActionMessage( e.getMessage()));
			// e.printStackTrace();
			saveErrors(request, errors);
			return mapping.findForward(Results.ERROR);
		}

	}

}
